package com.lambkit.web.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.StrUtil;
import com.lambkit.core.http.IController;
import com.lambkit.core.http.IRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HutoolShearSessionCaptcha implements ICaptcha {

    public void render(IController controller) {

        controller.getResponse().setHeader("Cache-Control", "no-store");
        controller.getResponse().setHeader("Pragma", "no-cache");
        controller.getResponse().setDateHeader("Expires", 0);
        controller.getResponse().setContentType("image/png");

        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(108, 40, 4, 2);

        // 验证码存入session
        controller.getSession().setAttribute("verifyCode", shearCaptcha.getCode());
        //Printer.print(this, "web"("verifyCode: " + getSession().getAttribute("verifyCode"));

        // 输出图片流
        try {
            shearCaptcha.write(controller.getResponse().getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public boolean validate(IRequest request, String userInputString) {
        if(StrUtil.isBlank(userInputString)){
            return false;
        }
        String shearCaptcha = (String) request.getSession(true).getAttribute("verifyCode");
        //Printer.print(this, "web"("verifyCode: " + getSession().getAttribute("verifyCode"));
        if(shearCaptcha==null || !shearCaptcha.equalsIgnoreCase(userInputString)) {
            return false;
        }
        return true;
    }
}
